﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using WebApi.Core.AuthHelper;
using WebApi.Core.Common.Helper;
using WebApi.Core.IService;
using WebApi.Core.Model;
using WebApi.Core.Model.Entity;
using WebApi.Core.Service;

namespace WebApi.Core.Controllers
{
    /// <summary>
    /// 用户管理
    /// </summary>
    //[Route("api/[controller]/[action]")]
    //[ApiController]
    public class JwtTestController : BaseController
    {
        public readonly PermissionRequirement _requirement;

        private readonly IUserService _userService;
        private readonly IUserRoleService _userRoleService;

        public JwtTestController(PermissionRequirement requirement,IUserService userService, IUserRoleService userRoleService)
        {
            _requirement = requirement;
            _userService = userService;
            _userRoleService = userRoleService;
        }

        #region MyRegion
        /// <summary>
        /// hello请求
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public IActionResult Hello()
        {
            return Ok("Hello World");
        }

        /// <summary>
        /// 获取User实体
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPost]
        [ApiExplorerSettings(IgnoreApi = true)]
        public IActionResult User(User user)
        {
            return Ok(user);
        }
        #endregion

        #region JWT
        [HttpPost]
        public IActionResult Login(string role)
        {
            string jwtStr = string.Empty;
            bool suc = false;

            if (!string.IsNullOrEmpty(role))
            {
                //将用户id和角色名，作为单独的自定义变量封装进 token 字符串中。
                TokenModel tokenModel = new TokenModel { Uid = "admin", Role = role };
                jwtStr = JwtHelper.IssueJwt(tokenModel);   //登录，获取到一定规则的 Token 令牌
                suc = true;
            }
            else
            {
                jwtStr = "login fail!!!";
            }

            return Ok(new
            {
                success = suc,
                token = jwtStr
            });
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="uId"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Login2(int uId)
        {
            string jwtStr = string.Empty;
            bool suc = false;

            if (uId > 0)
            {
                var user = await _userService.QueryByID(uId);
                var userRoles = await _userRoleService.GetUserRoleByUserId(uId);
                if (userRoles.Count > 0)
                {
                    var userRolesStr = await _userRoleService.GetUserRoleNameStr(uId);
                    
                    //如果是基于用户的授权策略，这里要添加用户;如果是基于角色的授权策略，这里要添加角色
                    var claims = new List<Claim> {
                        new Claim(ClaimTypes.Name, user.UserName),
                        new Claim(JwtRegisteredClaimNames.Jti, uId.ToString()),
                        new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_requirement.Expiration.TotalSeconds).ToString()) 
                    };
                    claims.AddRange(userRolesStr.Split(',').Select(s => new Claim(ClaimTypes.Role, s)));

                    var token = JwtToken.BuildJwtToken(claims.ToArray(), _requirement);
                    //jwtStr = JwtToken.BuildJwtToken2(claims.ToArray(), _requirement);

                    return Ok(new
                    {
                        success = suc,
                        //token = jwtStr
                        token = token
                    });
                }
            }

            return Ok(new
            {
                success = suc,
                token = jwtStr
            });
        }

        /// <summary>
        /// 需要Admin权限
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize(Roles = "Admin")]
        public IActionResult Admin()
        {
            return Ok("hello admin");
        }


        /// <summary>
        /// 需要System权限
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize(Roles = "System")]
        public IActionResult System()
        {
            return Ok("hello System");
        }

        /// <summary>
        /// 需要System 和 Admin权限
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        //[Authorize(Roles = "SystemOrAdmin")]
        //使用策略进行鉴权
        [Authorize(Policy = "SystemOrAdmin")]
        public IActionResult SystemAndAdmin()
        {
            return Ok("hello SystemOrAdmin");
        }

        #region 测试自定义
        /// <summary>
        /// RolePolicy1
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize(Policy = "Permission")]
        public IActionResult RolePolicy1()
        {
            return Ok("hello RolePolicy1");
        }
        /// <summary>
        /// RolePolicy2
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize(Policy = "Permission")]
        public IActionResult RolePolicy2()
        {
            return Ok("hello RolePolicy2");
        }
        /// <summary>
        /// RolePolicy3
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize(Policy = "Permission")]
        public IActionResult RolePolicy3()
        {
            return Ok("hello RolePolicy3");
        }
        #endregion


        /// <summary>
        /// 解析Token
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        public IActionResult ParseToken()
        {
            //需要截取Bearer 
            var tokenHeader = HttpContext.Request.Headers["Authorization"].ToString().Replace("Bearer ", "");
            var user = JwtHelper.SerializeJwt(tokenHeader);
            return Ok(user);
        }

        #endregion


        /////////////////////////////////////////////////////////////


        [HttpGet]
        public async Task<IActionResult> GetUser(int id)
        {
            UserEntity user = await _userService.QueryByID(id);

            return Ok(user);
        }


    }
}